package com.ssm.common;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 页面拦截
 *
 * @author sujinran
 * @Time 17:25 2017/10/26
 */
public class LoginInterceptor implements HandlerInterceptor {

    //在执行handler之前 运行这个方法里面的代码
    //用户登录验证
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //获取请求页面的相对路径
        String requestUri = request.getRequestURI();
        //将不需要验证的地址(公开地址)滤掉，string login = "login";requestUri.indexOf("")获得在请求路径中获得下标
        if (requestUri.indexOf("login") >= 0 || requestUri.indexOf("toLogin.do") >= 0) {
            return true;
        }
        System.out.println("进入拦截器 ：URL---------" + requestUri);
        HttpSession session = request.getSession();
        //检查用户id   用Session.getAttibute（String key）来获得Session对象中含有的关键字是key的对象
        Integer uid = (Integer) request.getSession().getAttribute("uid");
        // User user = (User) session.getAttribute("user");//自己设定的一个索引关键字
        //用户id为空跳转到登录页面
        if (uid == null) {
            request.getRequestDispatcher("/WEB-INF/view/login.jsp").forward(request, response);
            return false;
        } else {
            return true;
        }
    }

    //在执行handler ,返回modelAndView之前 运行这个方法里面的代码
    //向页面提供一些公用的数据或者视图信息,
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }


    //执行handler之后 运行这个方法来面的代码
    //系统统一的异常处理,方法执行时间 :afterCompletion-preHandler
    //系统日志记录
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}
